/**
 *
 * The MIT License
 *
 * Copyright (c) 2008 Board of Trustees, Leland Stanford Jr. University. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.macdadi.core.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.macdadi.core.client.auth.AuthService;
import org.macdadi.core.client.auth.AuthenticatedUser;
import com.mysql.jdbc.Driver;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Ben Suter <ben.suter@gmail.com>
 */
public class AuthServiceImpl extends RemoteServiceServlet implements AuthService
{
    protected static final String COL_ID = "id";
    protected static final String COL_NAME = "name";
    protected static final String COL_EMAIL = "email";

    protected transient Connection db;
    protected final String dbPropertiesFile = "database.properties";
    protected final String dbPropertiesDriverClass = "driverclass";
    protected final String dbPropertiesConnectionString = "connectionstring-write";

    public AuthServiceImpl() {
        super();

        /* Setup the DB connection */
        try {
            Properties dbProps = new Properties();
            dbProps.load(getClass().getResourceAsStream("database.properties"));

            Class.forName(dbProps.getProperty(dbPropertiesDriverClass));
            db = DriverManager.getConnection(dbProps.getProperty(dbPropertiesConnectionString));
        } catch (IOException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Authenticate a user. If the authentication succeeds, either
     * a new session is established, or an existing session is
     * extended.
     *
     * @param email     identifies the user (case-sensitive)
     * @param password  authenticates the user (case-sensitive)
     * @return          true if the credentials are valid
     */
    public AuthenticatedUser login(String email, String password)
    {
        if ( email == null || password == null )
            return null;

        try {            
            String call = "call auth_login(?,?,?)";
            CallableStatement cs = db.prepareCall(call);
            cs.setString(1, email); // p_email
            cs.setString(2, password);  // p_password
            cs.registerOutParameter(3, Types.VARCHAR);  // p_token
            boolean isResultSet = cs.execute();
            String authToken = cs.getString(3);

            if ( authToken == null ) {
                cs.close();
                return null;
            }

            if ( ! isResultSet ) {
                cs.close();
                return null;
            }

            ResultSet r;
            r = cs.getResultSet();

            if ( r.next() ) {
                AuthenticatedUser user = new AuthenticatedUser();
                user.setId(r.getInt(COL_ID));
                user.setName(r.getString(COL_NAME));
                user.setAuthToken(authToken);
                user.setEmail(r.getString(COL_EMAIL));

                /* If a list of authorized operations is returned, add these */
                isResultSet = cs.getMoreResults();
                if ( isResultSet ) {
                    ArrayList<String> ops = new ArrayList<String>();
                    r = cs.getResultSet();
                    while ( r.next() ) {
                        /* project-target-operation */
                        ops.add(r.getInt(1) + ":" + r.getString(2) + ":" + r.getString(3));
                    }
                    user.setAuthorizedOperations(ops.toArray(new String[ops.size()]));
                }
                
                cs.close();
                return user;
            }

            cs.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * Terminate the specified user's session. The user must be
     * currently authenticated for this method to succeed.
     *
     * @param user  a user with a current session
     * @return      true if no session remains for this user
     */
    public boolean logout(AuthenticatedUser user)
    {
        if ( user == null )
            return false;

        boolean success = false;

        try {
            String call = "call auth_logout(?,?,?)";
            CallableStatement cs = db.prepareCall(call);
            cs.setString(1, user.getEmail()); // p_email
            cs.setString(2, user.getAuthToken());  // p_token
            cs.registerOutParameter(3, Types.BOOLEAN);  // p_success
            cs.executeQuery();
            success = cs.getBoolean(3);

            cs.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return success;
    }

    /**
     * Find the authenticated user for the specified session.
     * If the session is not valid, or if no such session exists,
     * null is returned.
     *
     * @param   email       the email (username) of the user
     * @param   authToken   a current session identifier
     * @return              null if session invalid or non-existent, otherwise an authenticated user
     */
    public AuthenticatedUser getUserForSession(String email, String authToken)
    {
        if ( authToken == null )
            return null;

        try {
            String call = "call auth_check_session(?, ?,?)";
            CallableStatement cs = db.prepareCall(call);
            cs.setString(1, email); // p_email
            cs.setString(2, authToken); // p_token
            cs.registerOutParameter(3, Types.BOOLEAN);  // p_success
            boolean isResultSet = cs.execute();
            boolean success = cs.getBoolean(3);

            if ( ! success ) {
                cs.close();
                return null;
            }

            if ( ! isResultSet ) {
                cs.close();
                return null;
            }

            ResultSet r;
            r = cs.getResultSet();

            if ( r.next() ) {
                AuthenticatedUser user = new AuthenticatedUser();
                user.setId(r.getInt(COL_ID));
                user.setName(r.getString(COL_NAME));
                user.setAuthToken(authToken);
                user.setEmail(r.getString(COL_EMAIL));

                /* If a list of authorized operations is returned, add these */
                isResultSet = cs.getMoreResults();
                if ( isResultSet ) {
                    ArrayList<String> ops = new ArrayList<String>();
                    r = cs.getResultSet();
                    while ( r.next() ) {
                        /* project-target-operation */
                        ops.add(r.getInt(1) + ":" + r.getString(2) + ":" + r.getString(3));
                    }
                    user.setAuthorizedOperations(ops.toArray(new String[ops.size()]));
                }

                cs.close();
                return user;
            }

            cs.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * Determines whether the user authenticated with <code>authToken</code
     * is permitted to view domain for the specified project. Generally the
     * result is true if the project is public or the user is an active
     * member of the project.
     *
     * @param authToken     token identifying an authenticated user
     * @param projectId     the project in question
     * @return              true if the user may view domain for the project
     */
    public boolean isAuthorizedProjectRead(String authToken, int projectId)
    {        
        boolean success = false;

        try {
            String call = "call auth_check_project_read(?,?,?)";
            CallableStatement cs = db.prepareCall(call);
            cs.setString(1, authToken); // p_token
            cs.setInt(2, projectId);  // p_project
            cs.registerOutParameter(3, Types.BOOLEAN);  // p_success
            cs.executeQuery();
            success = cs.getBoolean(3);

            cs.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return success;
    }

    /**
     * Determine whether the user authenticated with <code>authToken</code>
     * has permission to perform <code>operation</code> against <code>target</code>
     * for the specified project. This method is intended for use by client-side code
     * that exposes editing controls only to users who are permitted to perform such
     * modifications.
     * <p/>
     * To check whether the current user is permitted to modify a goal, the call
     * would look something like this (though usually it is called through an asynchronous
     * interface, see the convenience method <code>Main.checkOperationAuthorized</code>):
     * <code>isAuthorizedOperation(currentAuthToken, currentProjectId, TARGET_GOALS, OPERATION_EDIT);</code>
     * <p/>
     * Implementation note: This method invokes the <code>auth_check_operation</code>
     * stored procedure, which is used internally by other stored procedures to
     * check the role-based permissions for any modifications to domain.
     *
     * @param authToken token identifying an authenticated user
     * @param projectId identifies the project
     * @param target    a domain collection, one of the TARGET_XXX constants
     * @param operation the type of modification, one of the OPERATION_XXX constants
     * @return true if the user may perform the modification
     */   
    
    //TODO: HOW IS THIS DIFFERENT FROM THE ONE IN AUTHENTICATED USER?
    
    public boolean isAuthorizedOperation(String authToken, int projectId, String target, String operation)
    {
        boolean success = false;

        try {
            String call = "SELECT auth_check_operation(?,?,?,?);";
            PreparedStatement ps = db.prepareStatement(call);

            ps.setString(1, authToken); // p_token
            ps.setInt(2, projectId);  // p_project
            ps.setString(3, target); // p_target
            ps.setString(4, operation); // p_operation
            ResultSet rs = ps.executeQuery();
            if ( rs.next() )
                success = rs.getBoolean(1);

            ps.close();
        } catch (SQLException ex) {
            Logger.getLogger(DataServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return success;
    }
}